<template>
    <el-row :gutter="30">
     <el-col :span="18">
         <div v-if="article" class="styled-article">
             <div class="article-header">
                 <h1 class="title">{{ article.title }}</h1>
                 <div class="article-statistics">
<!--                 文章数据中的用户ID 转换为用户名 -->
                <span class="stat-item">作者:  {{ articlAuthor.username }}</span>
                 </div>
                 <div class="article-meta">
                     <span>评论数: {{ article.comment }}| 点赞数: {{ article.likesTotalNums }}
                          | 浏览数:{{ article.skimNum }}| 创建时间: {{ article.createTime }}</span>
                 </div>
                 <div class="meta-info">
                     <p>摘要:{{ article.articleSummary }}</p>
                 </div>
             </div>
             <!--        加条横线-->
             <hr></hr>
             <div class="article-media">
<!--                 <img :src="'/project/files'+article.imgUrl" alt="Article Image" class="article-image">-->
                 <el-image :src="baseUrl+article.imgUrl" alt="菜谱图片" class="article-image"></el-image>
             </div>
             <div class="article-body">
                 <div class="article-content">
                     <p>{{ article.content }}</p>
                 </div>
             </div>
             <div class="action-buttons">
<!--               如果收藏状态为true 则显示已收藏图标，否则显示收藏图标 if  两个方法-->




                 <el-button @click="handleCollect" class="styled-button collect" v-if="!collectStatus"><el-icon><Star /></el-icon>收藏</el-button>
                 <el-button @click="handleDeleteCollect" class="styled-button discollect" v-else><el-icon><Star /></el-icon>取消收藏</el-button>
               <!--根据点赞状态显示不同的图标 如果为true 则显示已点赞图标，否则显示点赞图标-->
               <el-button @click="handleLike" :class="{ liked: likeStatus }" class="styled-button like">
                 <el-icon><el-icon :size="20"><Pointer v-if="likeStatus" /><Pointer v-else /></el-icon></el-icon>
                 {{ likeStatus ? '取消点赞' : '点赞' }}
               </el-button>


                 <el-button @click="handleComment" class="styled-button comment"> <el-icon><ChatDotSquare /></el-icon>评论</el-button>


                 <!-- 点击按钮弹出评论弹窗 -->
                 <el-dialog v-model="dialogVisible" title="评论" width="30%">
                     <el-input type="textarea" placeholder="请输入评论内容" v-model="commentContent"></el-input>
                     <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="cancleComment">取 消</el-button>
                        <el-button type="primary" @click="handleCommentConfirm">确 定</el-button>
                    </span>
                     </template>
                 </el-dialog>
             </div>
         </div>
     </el-col>
    <el-col :span="6" >
        <el-card class="user-card">
            <!-- 用户信息 -->

            <div class="user-info">
<!--                <img :src="userData.img_url" alt="User Avatar" class="user-avatar">-->
                <el-image :src="baseUrl+articlAuthor.imgUrl" alt="User Avatar" class="user-avatar"></el-image>
                <div class="user-details">
                    <p>{{ articlAuthor.username }}</p>
                    <p><el-icon><EditPen /></el-icon>本文作者</p>
                    <p><el-icon><Clock /></el-icon>{{article.createTime}}</p>
                </div>
            </div>
        </el-card>
        <el-card class="recommend-card">
            <h2 style="font-weight: lighter">您愿意向朋友推荐此文章吗？</h2>
            <el-divider></el-divider>
            <div class="rating-section">
                <el-rate v-model="rateValue"></el-rate>
            </div>
        </el-card>
<!--        展示评论内容-->
        <el-card class="comment-card">
            <h2 style="font-weight: lighter">文章评论<el-icon><ChatDotRound /></el-icon></h2>
            <div class="comment-list">
                <div v-for=" item in comments" :key="item.id">
                    <div class="comment-item">
                        <div class="comment-header">
                            <span class="comment-author"><el-icon><UserFilled /></el-icon> {{ userIdFormatter(item , null,item.userId, null) }} </span>
                    <!--                            评论内容-->
                            <span class="comment-content">{{ item.commentText }}</span>
                            <span class="comment-time">{{ item.createTime }}</span>
<!--                            todo-->
<!--                            判断当前登录的用户 和发布的用户id是否一致 如果一致显示删除按钮-->
                            <span v-if="user.id === item.userId">
                                <el-button
                                        type="danger" @click="deleteComment(item.id)" icon="delete"
                                        style="margin-left: 100px;"></el-button>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </el-card>


    </el-col>
    </el-row>
</template>



<script setup>
import axios from 'axios';
import {onMounted, ref} from 'vue';
import qs from "qs";
import {ElMessage} from "element-plus";


//获取从社区模块传过来的文章id
const baseUrl = getBaseUrl();
const urlParams = new URLSearchParams(window.location.search);
const articleId = urlParams.get('id');
console.log("111",articleId);
const  user =ref(getUser());


// 用户ID 转换为用户名
const userIdFormatter = (row, column, cellValue, index) => {
    if (cellValue==101){
        return 'user1';
    }else if (cellValue == 102){
        return 'user2';
    }else if (cellValue == 103){
        return 'user3';
    }
 return cellValue;

}

//定义变量用于存储本文作者的数据
const articlAuthor = ref([]);

const loadArticlAuthor = (userId) => {
    axios.get(BASE_URL+'/v1/user/queryMessage/'+userId)
        .then(response => {
            if (response.data.code === 2000) {
               articlAuthor.value = response.data.data[0];
               console.log("bbbbbbbbbbbbb"+articlAuthor.value);
               console.log(response.data.data);
           } else {
               alert(response.data.msg);
           }
        })

};

// 定义方法获取文章详情
const LoadArticleDetails = () => {
    axios.get(BASE_URL+'/v1/article/details/select?articleId='+articleId+"&userId="+user.value.id)
        .then((response) => {
            if (response.data.code === 2000) {
                article.value = response.data.data;
                loadArticlAuthor(article.value.userId)
              if(article.value.thumbsUpStatus == '1') {
                likeStatus.value = true;
              }
              if(article.value.favoriteStatus == '1') {
                collectStatus.value = true;
              }
            } else {
                alert(response.data.msg);
            }
        });
};

// 初始化文章数据
const article = ref('');

//页面开始就加载
onMounted(()=>{
   LoadArticleDetails();
   viewComments();
})

// 初始化点赞状态
const likeStatus = ref(false);
// 初始化收藏状态
const collectStatus = ref(false);

/**
 * 处理收藏文章的操作
 */
//文章取消收藏 文章详情页 收藏点赞 查询
const handleCollect = () => {
    let data1 = {
        articleId: article.value.id,
        userId: user.value.id, // 假设当前用户 ID 为 101
        status: '1'
    };
    let data = qs.stringify(data1);
    axios.post(BASE_URL+'/v1/article/favorites/save', data)
        .then((response) => {
            if (response.data.code === 2000) {
                ElMessage.success('收藏成功');
                collectStatus.value=true;
            } else {
                ElMessage.error(response.data.msg);
            }
        });
};
const handleDeleteCollect=() =>{
    let data1 = {
        ids: [article.value.id],
        userId: user.value.id, // 假设当前用户 ID 为 101
    };
    let data = qs.stringify(data1);
    axios.post(BASE_URL+'/v1/article/favorites/remove', data)
        .then((response) => {
            if (response.data.code === 2000) {
                ElMessage.success('取消收藏成功');
                collectStatus.value=false;
            }
        })
};

/**
 * 处理点赞文章的操作
 */
const handleLike = () => {
    likeStatus.value = !likeStatus.value;
    let data1 = {
        articleId: article.value.id,
        userId: user.value.id, // 假设当前用户 ID 为 101
        status: likeStatus.value ? '1' : '0'
    };
    let data = qs.stringify(data1);
    axios.post(BASE_URL+'/v1/article/thumbsUp/save', data)
        .then((response) => {
            if (response.data.code === 2000) {
                ElMessage.success('操作成功');
            } else {
                ElMessage.error(response.data.msg);
            }
        });
};

/**
 * 处理评论文章的操作
 */
const dialogVisible = ref(false);
const commentContent = ref('');
const handleComment = () => {
    dialogVisible.value = true;
};
const handleCommentConfirm = () => {
    let data1 = {
        articleId: article.value.id,
        userId: user.value.id, // 假设当前用户 ID 为 101
        commentText: commentContent.value
    };
    let data = qs.stringify(data1);
    axios.post(BASE_URL+'/v1/article/comment/save', data)
        .then((response) => {
            if (response.data.code === 2000) {
                alert('评论成功');
                viewComments();
            } else {
                alert(response.data.msg);
            }
        });
    dialogVisible.value = false;
};
/**
 * 取消评论按钮
 */
const cancleComment = () => {
    if (confirm('确认要取消评论吗？')){
    dialogVisible.value = false;
    commentContent.value = '';
    }
};
//如果是自己发的评论可以删除
const deleteComment = (commentId) => {
    if (confirm('确认要删除评论吗？')){
    axios.post(BASE_URL + '/v1/article/comment/delete?commentId=' + commentId)
        .then((response) => {
            if (response.data.code === 2000) {
                ElMessage.success('评论删除成功');
                viewComments();
            }
            else {
                ElMessage.error(response.data.msg);
            }
        });
    }
}


/**
 * 查看评论详情
 */
// 初始化评论列表
const comments = ref([
    // {
    //     id: 1,
    //     userId: 101,
    //     userName: '张三',
    //     content: '这个文章不错！',
    //     createTime: '2023-07-01'
    // },
]);
const commentsDialogVisible = ref(false);
/**
 * 查看评论详情
 */
const viewComments = () => {
    commentsDialogVisible.value= true;
    axios.get(BASE_URL+'/v1/article/comment/select?articleId='+articleId)
        .then((response) => {
            if (response.data.code === 2000) {
                comments.value = response.data.data;
            }else if (response.data.code===4008){
                ElMessage.warning('暂无评论');

            }
            else {
                ElMessage.error(response.data.msg);
            }
        });
};
/**
 * 删除评论/
 */




const rateValue = ref(0);

</script>


<style scoped>
/* 新增的样式 */
.styled-article {
    /*border-left: 5px solid #ddd; !* 左侧简单花边装饰 *!*/
    padding: 20px;
    margin: 20px;
    width: 90%;
    background-color: #f9f9f9;
    position: relative;
}

.stat-item {
    margin: 0 5px; /* 添加一些间距 */
}
.article-statistics {
    color: #777;
    font-size: 10px;
    display: flex;
    justify-content: space-between; /* 横向均匀分布 */
    align-items: center; /* 垂直居中对齐 */
    padding: 5px;
    border-radius: 5px;
    background-color: #f9f9f9;

}
.article-meta{
    color: #777;
    font-size: 10px;
    flex: 1; /* 每个统计项占据相等的空间 */
    text-align: center; /* 文本居中对齐 */
    padding: 0 10px; /* 内边距 */

}

.stat-item {
    flex: 1; /* 每个统计项占据相等的空间 */
    text-align: center; /* 文本居中对齐 */
    padding: 0 10px; /* 内边距 */
}

.stat-item p {
    margin: 0; /* 移除默认的段落间距 */
    font-size: 10px; /* 设置字体大小 */
    color: #333; /* 设置文本颜色 */
}

.title {
    color: goldenrod;
    margin-bottom: 10px;
    font-size: 25px;
    text-align: center;
}

.meta-info {
    color: #777;
    font-size: 15px;
    text-align: center;
}
.article-media{
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中（如果需要） */
    margin-bottom: 20px;
}
.article-image {
    max-width: 100%;
    height: 300px;
    width: auto;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    display: inline-block; /* 确保图片作为内联块级元素 */
    padding: 10px;
}
.article-video{
    max-width: 80%;
    height: 300px;
    width: auto;
}

.styled-button {
    padding: 10px 20px;
    font-size: 0.9em;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.2s ease-in-out;
}

.collect {
  background-color: #2196F3;
  color: white;
}
.discollect{
  background-color: #BBDEFB;
  color: white;
}

.like {
    background-color: #2196F3;
    color: white;
}

.liked {
    background-color: #BBDEFB;

}

.comment {
    background-color: #FF9800;
    color: white;
}


.action-buttons button:not(:last-child) {
    margin-right: 10px;
}

/*左侧*/
.user-card {
    border-radius: 20px; /* 设置卡片的圆角 */
    width: 100%;
}

.user-info {
    display: flex;
    align-items: center;
    justify-content: center; /* 水平居中 */
    flex-direction: column; /* 垂直排列子元素 */
    padding: 16px; /* 添加内边距以确保内容不紧贴边缘 */
}

.user-avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%; /* 头像圆形 */
    margin-right: 10px;

}

.user-details {
    flex: 1;
    font-size: 15px;
    color:#777;
    text-align: center;
}
.recommend-card {
    margin-top: 10px;
    border-radius: 20px; /* 设置卡片的圆角 */
    padding: 16px; /* 添加内边距以确保内容不紧贴边缘 */
}

.rating-section {
    display: flex;
    justify-content: center; /* 水平居中对齐评分组件 */
    margin-top: 10px; /* 在标题和评分组件之间添加间距 */
}
.comment-card{
    border-radius: 20px;
    padding: 16px;
    margin-top: 10px;
}
.comment-author{
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 10px;
}
.comment-time{
    color: #777;
    font-size: 12px;
}
</style>

